package com.zch.rpc.client.client;

import com.zch.rpc.client.common.model.RequestModel;
import com.zch.rpc.client.common.model.ResponseModel;

import java.io.*;
import java.net.Socket;

/**
 * 链接服务器调用服务
 * @author QJM
 *
 */
public class RpcClient {
	
	public Object start(RequestModel request, String host, int port) throws Throwable{
		//发起socket连接请求
		Socket server = new Socket(host, port);
		
		InputStream in = null;
		ObjectInputStream oin = null;
		OutputStream out = null;
		ObjectOutputStream oout = null;
		try {
			// 1. 发送请求数据
			out = server.getOutputStream();
			oout = new ObjectOutputStream(out);
			//将整个对象塞进输出流里  （对象要序列化）
			oout.writeObject(request);
			oout.flush();
			
			// 2. 获取返回数据，强转参数类型
			in = server.getInputStream();
			oin = new ObjectInputStream(in);
			Object res = oin.readObject();
			ResponseModel response = null;
			if(!(res instanceof ResponseModel)){
				throw new RuntimeException("返回参数不正确");
			}else{
				response = (ResponseModel) res;
			}
			
			// 3. 返回结果
			if(response.getError() != null){ //服务器产生异常(如果有异常服务端会将异常晒进去)
				throw response.getError();
			}
			return response.getResult();
		}finally{
			try {	//关闭流
				if(in != null) in.close();
				if(oin != null) oin.close();
				if(out != null) out.close();
				if(oout != null) oout.close();
				if(server != null) server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
